namespace :whenever do
  desc '账户月报生成'
  task monthly: :environment do
    report_date = Date.current.at_beginning_of_month - 1.months
    xlsx = "#{Rails.public_path}/xlsx/月账单-#{report_date}.xls"
    book = Spreadsheet::Workbook.new
    sheet = book.create_worksheet
    sheet.name = '月账单'
    sheet.row(0).concat(%w"行为 类型 内容 备注 额度 批次号 日期")
    Company.all.each do |cp|
      WalletTransLog.search(company_id_eq: cp.id, created_at_gteq_datetime: report_date, created_at_lteq_datetime: report_date + 1.weeks).result.each_with_index {|log, ind|
        sheet.row(ind + 1).concat(log.slice(:action_i18n, :kind_i18n, :title, :remark, :amount, :batch_no, :created_at).values)
      }
    end
    book.write(xlsx)
  end

  desc '账户周报生成'
  task weekly: :environment do
    report_date = Date.current.at_beginning_of_week - 1.weeks
    xlsx = "#{Rails.public_path}/xlsx/周账单-#{report_date}.xls"
    book = Spreadsheet::Workbook.new
    Company.all.each do |cp|
      logs = WalletTransLog.search(company_id_eq: cp.id, created_at_gteq_datetime: report_date, created_at_lteq_datetime: report_date + 1.weeks).result
      if logs.count(1) > 0
        sheet = book.create_worksheet
        sheet.name = cp.name
        sheet.row(0).concat(%w"行为 类型 内容 备注 额度 批次号 记录时间")
        logs.each_with_index {|log, ind|
          sheet.row(ind + 1).concat(log.slice(:action_i18n, :kind_i18n, :title, :remark, :amount, :batch_no, :created_at).values)
        }
      end
    end
    book.write(xlsx)
  end

  desc '工资'
  task salary: :environment do
    report_date = Date.today.at_beginning_of_month
    SalaryJob.perform_now([-1], [-1], report_date - 1.months, report_date)
  end
end
